package com.xxx.springboot.util;

import com.xxx.springboot.service.DistributedLocker;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

/**
 * 【redisson分布式锁】3.Redisson分布式锁工具类
 */
public class RedissLockUtil {
	
	private static DistributedLocker redissLock;

	// setter注入DistributedLocker
	public static void setLocker(DistributedLocker redissLocker) {
		redissLock = redissLocker;
	}
	
	/**
	 * 给指定key加锁，默认超时时间
	 * @param lockKey
	 * @return
	 */
	public static RLock lock(String lockKey) {
		return redissLock.lock(lockKey);
	}
	
	/**
     * 带超时的锁
     * @param lockKey
     * @param unit 时间单位
     * @param timeout 超时时间
     */
    public static RLock lock(String lockKey, TimeUnit unit ,int timeout) {
        return redissLock.lock(lockKey, unit, timeout);
    }
    
    /**
     * 尝试获取锁
     * @param lockKey
     * @param waitTime 最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        return redissLock.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime);
    }
    
    /**
     * 尝试获取锁
     * @param lockKey
     * @param unit 时间单位
     * @param waitTime 最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        return redissLock.tryLock(lockKey, unit, waitTime, leaseTime);
    }

	/**
	 * 解锁
	 */
	public static void unlock(String lockKey) {
		redissLock.unLock(lockKey);
	}
	
	/**
	 * 解锁
	 */
	public static void unlock(RLock lock) {
		redissLock.unLock(lock);
	}
	
}
